import Const from "./const";
import {mapState} from 'vuex'

function Socket() {
    let socket = null;
    let timer = null;
    let socketMsgQueue = [];

    return {
        init: init,
        sendMsg: sendMsg,
        clear: clear
    };

    function init() {
        if (!mapState.websocket) {
            socket = uni.connectSocket({
                url: Const.NET.END_POINT_WS,
                success: () => {
                    console.log('socket创建成功')
                }
            });
            this.$store.commit("initWebsocket", socket)
        } else {
            socket = mapState.websocket;
        }

        socket.onOpen(() => {
            console.log('ws连接, readyState=' + socket.readyState)
            while (socketMsgQueue.length > 0) {
                let msg = socketMsgQueue.shift();
                sendMsg(msg);
            }
        });

        socket.onMessage(res => {
            if (res) {
                console.log(res, 111)
            }
        });

        socket.onError(() => {
            console.log('ws错误, readyState=' + socket.readyState)
            clear.apply(this)
        });

        socket.onClose(() => {
            console.log('ws关闭！readyState=' + socket.readyState)
            clear.apply(this)
        });

        timer = setInterval(() => {
            heartbeat();
        }, 5000);
    }

    function sendMsg(msg) {
        return new Promise((resolve, reject) => {
            if (socket.readyState === 1) {
                socket.send({
                    data: msg
                });
                resolve(msg)
            } else {
                socketMsgQueue.push(msg);
                reject(msg)
            }
        })
    }

    function clear() {
        let $this = this;
        socket.close({
            success() {
                $this.$store.commit("initWebsocket", null)
                console.log('socket关闭成功')
            }
        });
        clearInterval(timer);
        timer = null;
    }

    function heartbeat() {
        console.log("发送心跳");
        sendMsg(JSON.stringify({val: 'heartbeat'}));
    }
}

export default new Socket()
